#include "StdAfx.h"
#include "CorGame.h"
#include "Game.h"
#include "Terrain.h"
#include "camera.h"
#include "CGFunction.h"
Game::Game(void)
{
}

Game::~Game(void)
{
	DXMgr.shutdown();
	delete m_pTerrain;
}
void Game::PreRender()
{
	// Get the time before rendering
	QueryPerformanceCounter(&timeStart);
	// Call your render function
	DXMgr.beginRender();
}

void Game::Render()
{
	PreRender();
	m_pTerrain->Render();
	for (std::vector<CGameObject*>::const_iterator it=m_GameObject.begin();it!=m_GameObject.end();it++)
	{
		((CGameObject*)(*it))->render(DXMgr.getD3DDevice());
	}
	SceneMgr.Render();
	EndRender();
}
void Game::EndRender()
{
	DXMgr.endRender();
	// Get the updated time
	QueryPerformanceCounter(&timeEnd);
	// Determine the animation rate
	anim_rate = ( (float)timeEnd.QuadPart-(float)timeStart.QuadPart ) /timerFreq.QuadPart;
}
void Game::shutdown()
{

}

int Game::update()
{
	static float timeDelta=0.0f;
	static float timeNow=timeGetTime();
	timeDelta=timeGetTime()-timeNow;
	timeNow=timeGetTime();
	if( ::GetAsyncKeyState(VK_UP) & 0x8000f )
		m_pCamera->walk(1.0f * timeDelta);

	if( ::GetAsyncKeyState(VK_DOWN) & 0x8000f )
		m_pCamera->walk(-1.0f * timeDelta);

	if( ::GetAsyncKeyState(VK_LEFT) & 0x8000f )
		m_pCamera->fly(-1.0f * timeDelta);

	if( ::GetAsyncKeyState(VK_RIGHT) & 0x8000f )
		m_pCamera->fly(1.0f * timeDelta);

	if( ::GetAsyncKeyState('A') & 0x8000f )
		m_pCamera->strafe(-1.0f * timeDelta);

	if( ::GetAsyncKeyState('D') & 0x8000f )
		m_pCamera->strafe(1.0f * timeDelta);

	if( ::GetAsyncKeyState('W') & 0x8000f )
		m_pCamera->pitch(timeDelta/1000.0f);

	if( ::GetAsyncKeyState('S') & 0x8000f )
		m_pCamera->pitch(timeDelta/-1000.0f);

	D3DXMATRIX V;
	m_pCamera->getViewMatrix(&V);
	(DXMgr.getD3DDevice())->SetTransform(D3DTS_VIEW, &V);
	D3DXMATRIX proj;
	D3DXMatrixPerspectiveFovLH(
		&proj,
		D3DX_PI * 2/3, // 120 - degree
		840 / 680.0f,
		1.0f,
		4000.0f);
	(DXMgr.getD3DDevice())->SetTransform(D3DTS_PROJECTION, &proj);
	return 0;
}

bool Game::init(HWND wndHandle)
{
	CG::CGCheck(S_OK==DXMgr.Init(wndHandle));
	CG::CGCheck(BaseDataMgr.InitBaseData());
	CG::CGCheck(SceneMgr.InitData());
	m_pTerrain= new Terrain(DXMgr.getD3DDevice(), "..\\Resource\\Texture\\HighMap.bmp", 256, 256, 64, 0.5f);
	m_pTerrain->loadTexture(TEXT("..\\Resource\\Texture\\TerrainTex.jpg"));
	m_pCamera=new Camera(Camera::LANDOBJECT);
	return true;
}